package com.twu.biblioteca.menu;

import com.twu.biblioteca.BibliotecaApp;
import com.twu.biblioteca.model.Book;
import com.twu.biblioteca.model.User;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Iterator;
import java.util.List;

/**
 * @author Aaron Edwards
 * @since 24/09/13
 *        Menu item used to reserve a book in the library collection.<br/>
 *        The method will only reserve a book if the title is in the current collection and the book is not already reserved
 */
public class ReserveBookMenuItem implements IMenuItem {
    @Override
    public String getMenuTitleForUser(User currentUser) {
        return "Reserve Book";
    }

    @Override
    public void doAction(BibliotecaApp bibliotecaApp) {

        if (bibliotecaApp.getCurrentUser() == null) {

            bibliotecaApp.getOutputStream().println("Please talk to a Librarian. Thank you.");

        } else { //A user is logged in
            try {
                bibliotecaApp.getOutputStream().print("Book Title to Reserve: ");
                BufferedReader bufferedReader = null;

                bufferedReader = new BufferedReader(new InputStreamReader(bibliotecaApp.getInputStream()));
                String bookTitle = bufferedReader.readLine();
                List<Book> bookList = bibliotecaApp.getBookCollection().getItemList();
                boolean found = false;
                Iterator<Book> bookIterator = bookList.iterator();
                while (bookIterator.hasNext() && !found) {
                    Book nextBook = bookIterator.next();
                    if (!nextBook.isReserved() && nextBook.getBookTitle().equals(bookTitle)) {
                        found = true;
                        nextBook.setReservedBy(bibliotecaApp.getCurrentUser());
                    }
                }

                if (found) {
                    bibliotecaApp.getOutputStream().println("Thank You! Enjoy the book.");
                } else {
                    bibliotecaApp.getOutputStream().println("Sorry we don't have that book yet.");
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
